<?php
/**
 * 2021-02-04
 * 自定义验证类
 * php5.6以上可以使用const定义数组常量，ide报错部分可忽略
 * */

namespace App\Rules;

use Illuminate\Support\Facades\Validator;

class CheckRule {
//定义规则及返回信息
    private $rule = [];
    private $messages = [];
    private $fild = [];
    private $validator = "";

    //验证
    public function __construct($fild, $rule, $messages) {
        $this->fild = $fild;
        $this->rule = $rule;
        $this->messages = $messages;
        //验证
        $this->validator = Validator::make($this->fild, $this->rule, $this->messages);
    }

    /**
     * 返回错误
     * @param int $type 错误格式，1表示默认错误，2表示字符串错误.
     */
    public function check($type=1) {
        $validator = $this->validator;
        if ($validator->fails()) {
            $errors = $validator->errors();
            return ["error" => 90000, "msg" => $errors->first(), "data" => ""];
        }
        //排除__token
        if(array_key_exists("_token",$this->fild)){unset($this->fild["_token"]);}
        return ["error" => 0, "msg" => "", "data" => $this->fild];
    }
}
